<template>
  <view class="w-full dflex padding-bottom-sm">
  	<view class="iconfont iconyanzheng margin-right"></view>
  	<view class="border-line flex1 dflex">
  		<input class="padding-sm flex1" type="number" data-key="code" maxlength="6" :focus="codeFocus" :value="code" @confirm="confirm" @input="inputChange" placeholder="请输入验证码" />
  		
  		<view class="pos-r">
  			<view class="vertical-line" style="right: calc(100% + 20rpx);"></view>
  			<view v-if="!send" class="padding-tb-sm ft-dark-4" @click="sendCode">发送验证码</view>
  			<view v-else class="padding-tb-sm ft-dark-4">{{code_time}}s 重新获取</view>
  		</view>
  	</view>
  </view>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()

const code = ref('')
const codeFocus = ref(false)
const send = ref(false)
const code_time = ref(60)

const props = defineProps({
  agreement: {
    type: Boolean,
    default: true
  },
  agreementContent: {
    type: String,
    default: ''
  },
  mobile: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'register'
  }
})

const emit = defineEmits(['change', 'confirm'])

const inputChange = (value) => {
  emit('change', value)
}

const sendCode = () => {
  if (send.value) return

  if (!props.agreement) {
    proxy.$api.msg(props.agreementContent)
    return
  }

  if (!props.mobile) {
    proxy.$api.msg('请输入手机号')
    return
  }

  if (!/(^1[0-9][0-9]{9}$)/.test(props.mobile)) {
    proxy.$api.msg('请输入正确的手机号码')
    return
  }

  send.value = true
  code_time.value = 30

  // 调用服务端发送验证码的 API
  proxy.$func.usemall.call('member/sendSmsCode', {
    mobile: props.mobile,
    type: props.type
  }).then((res) => {
    if (res.code === 200) {
      proxy.$api.alert('验证码已发送', () => {
				codeFocus.value = true
				const timer = setInterval(() => {
				  --code_time.value
				
				  if (code_time.value <= 0) {
				    clearInterval(timer)
				    send.value = false
				    code_time.value = 30
						return
				  }
				}, 1000)
				return
			})
    } else {
      send.value = false
      code_time.value = 30
			proxy.$api.msg(res.msg)
    }
  })
}

const confirm = () => {
  emit('confirm', code.value)
}
</script>

<style >
</style>
